<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-button :loading="exportLoading" class="item-gap" size="mini" type="warning" @click="onReportBtn">导出</el-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select
						v-model="searchParams.workshopId"
						:clearable="false"
						:option-list="workshopList"
						class="search-bar-item-size1 margin-5-0 item-gap"
						placeholder="车间"
						size="small"
						@change="onWorkshopChange"
					></jk-select>
					<jk-select
						v-model="searchParams.processCode"
						:clearable="true"
						:option-list="processList"
						class="search-bar-item-size1 margin-5-0 item-gap"
						placeholder="工序"
						size="small"
						value-key-name="code"
					></jk-select>
					<jk-date-picker
						v-model="searchParams.belongDate"
						:clearable="false"
						:disabled-future-time="true"
						class="search-bar-item-size2 margin-5-0 item-gap"
						placeholder="日期"
						size="small"
						@change="onDateChange"
					></jk-date-picker>
					<el-select
						v-model="searchParams.shiftId"
						:disabled="shiftList.length === 0"
						class="search-bar-item-size3 margin-5-0 item-gap"
						placeholder="报工班次"
						size="small"
					>
						<el-option
							v-for="item in shiftList"
							:key="item.id"
							:label="`${item.name} (${item.beginHour} ~ ${item.endHour})`"
							:value="item.id"
						></el-option>
					</el-select>
					<jk-search-input
						v-model="searchParams.machineName"
						class="search-bar-item-size2 margin-5-0 item-gap"
						clearable
						placeholder="机台名称"
						size="small"
						@on-search="onSearchBtn"
					/>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="jkTable" :data="tableData" :height="tableHeight + 20" :loading="tableLoading" border>
				<vxe-column
					field="machineName"
					fixed="left"
					:width="90"
					title="机台"
				></vxe-column>
				<!--<vxe-column
                    field="totalVal"
                    fixed="left"
                    :width="90"
                    title="机台总产量"
                ></vxe-column>-->
				<vxe-column
					field="machineProductRecordsList"
					:min-width="1500"
					title="分段"
				>
					<template #header>
						<time-list-header
							:search-params="searchParams"
						></time-list-header>
					</template>
					<template slot-scope="scope">
						<time-list
							:row="scope.row"
							:search-params="searchParams"
							:option-list="scope.row.machineProductRecordList || []"
						></time-list>
					</template>
				</vxe-column>
				<!--<vxe-column :width="100" align="center" fixed="right" title="操作">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-edit-button
								:permission-prefix="prefix"
								@click="handleEdit(scope.row)"
							></jk-edit-button>
						</div>
					</template>
				</vxe-column>-->
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-size="searchParams.pageSize"
					:page-sizes="searchParams.pageSizes"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:data-id="dataId"
			:dialog-state="saveDialogState"
			:page-type="pageType"
			:from-data="fromData"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, formatTime, pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import {
        productionMachineListPage
    } from '@/api/production/machineProductRecords';
    import timeList from './components/time-list';
    import { workforceManagementShiftGetByTime, workforcemanagementShiftPage } from '../../../api/schedule/shift';
    import filterProcessList from '../../../mixins/filter-process-list';
    import timeListHeader from './components/time-list-header';
    import exportExcel from './exportExcel';
    import { recordTypeList } from '../../../utils/jk/status-option-list';
    import { mathJsAdd } from '../../../utils/jk/jk-cals';
    export default {
        name: 'MachineProductionRecords',
        components: {
            timeListHeader,
            timeList,
            saveDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache, filterProcessList, exportExcel],
        data() {
            return {
                prefix: 'production:machineProductRecords',
                apiItem: {
                    'page': productionMachineListPage
                },
                shiftList: [],
                dataId: null,
                saveDialogState: false,
                pageType: 'edit',
                processList: [],
                workshopList: [],
                tableLoading: false,
                tableData: [],
                fromData: {},
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    typeId: null,
                    shutdownState: null,
                    processCode: null,
                    workshopId: null,
                    shiftId: null,
                    machineName: null,
                    startDateTime: '',
                    endDateTime: '',
                    belongDate: ''
                },
                recordTypeList: recordTypeList,
                currentScheduleShiftInfo: {}
            };
        },
        methods: {
            handleEdit(row) {
                this.saveDialogState = true;
                this.fromData = row;
                this.dataId = row.id;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.saveDialogState = e;
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            updateCeshiStyles() {
                this.$nextTick(() => {
                    const vxeCells = document.querySelectorAll('.vxe-cell');
                    vxeCells.forEach(cell => {
                        const ceshiElements = cell.querySelectorAll('.borderLine');
                        if (ceshiElements.length > 0) {
                            cell.style.padding = '0';
                            ceshiElements.forEach((element, index) => {
                                let paddingTop = '7px';
                                let paddingBottom = '7px';

                                if (index === 0) {
                                    paddingTop = '0px';
                                }
                                if (index === ceshiElements.length - 1) {
                                    paddingBottom = '0px';
                                }
                                element.style.padding = `${paddingTop} 10px ${paddingBottom} 10px`;
                                element.style.borderBottom = index === ceshiElements.length - 1 ? 'none' : '1px solid #dcdff6';
                            });
                        }
                    });
                });
            },
            getCurrentShiftInfoRequest() {
                if (!this.searchParams.workshopId || !this.searchParams.belongDate) {
                    // this.$set(this.searchParams, 'shiftId', null);
                    return;
                }
                const currentTime = formatTime(Date.now()).split(' ')[1];
                const dateTime = currentTime ? `${this.searchParams.belongDate} ${currentTime}` : formatTime(Date.now());
                return workforceManagementShiftGetByTime({
                    workshopId: this.searchParams.workshopId,
                    belongTime: dateTime
                }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        this.currentScheduleShiftInfo = resData.currentShiftInfo || {};
                        this.$set(this.searchParams, 'shiftId', this.currentScheduleShiftInfo.id);
                    }
                });
            },
            // 根据班次ID获取开始和结束时间
            getStartDateTimeAndEndDateTimeByShiftId() {
                let startDateTime = '';
                let endDateTime = '';
                const shiftItem = this.shiftList.find(x => x.id === this.searchParams.shiftId) ? this.shiftList.find(x => x.id === this.searchParams.shiftId) : null;
                if (shiftItem) {
                    const startHour = shiftItem.beginHour.split(':') && shiftItem.beginHour.split(':').length ? Number(shiftItem.beginHour.split(':')[0]) : 0;
                    const endHour = shiftItem.endHour.split(':') && shiftItem.endHour.split(':').length ? Number(shiftItem.endHour.split(':')[0]) : 0;
                    if (endHour < startHour) {
                        startDateTime = `${this.searchParams.belongDate} ${shiftItem.beginHour}:00`;
                        endDateTime = `${formatDate(Date.parse(this.searchParams.belongDate) + 24 * 60 * 60 * 1000)} ${shiftItem.endHour}:00`;
                    } else {
                        startDateTime = `${this.searchParams.belongDate} ${shiftItem.beginHour}:00`;
                        endDateTime = `${this.searchParams.belongDate} ${shiftItem.endHour}:00`;
                    }
                    this.$set(this.searchParams, 'startDateTime', startDateTime);
                    this.$set(this.searchParams, 'endDateTime', endDateTime);
                }
            },
            /** 查询列表 */
            getListRequest() {
                if (!this.searchParams.belongDate || !this.searchParams.shiftId) {
                    this.tableData = [];
                    return;
                }
                this.getStartDateTimeAndEndDateTimeByShiftId();
                const params = JSON.parse(JSON.stringify(this.searchParams));
                // delete params.belongDate;
                delete params.shiftId;
                return this.apiItem['page'](params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        const resData = res.data.res || [];
                        this.tableData = resData.map(machineItem => {
                            // 统计单个机台的总产量
                            machineItem.totalVal = 0;
                            machineItem.machineProductRecordList.forEach(timeItem => {
                                machineItem.totalVal = mathJsAdd(machineItem.unit === 'kg' ? timeItem.outputKg : timeItem.outputM, machineItem.totalVal);
                            });
                            return machineItem;
                        });
                        this.updateCeshiStyles();
                        this.totalCount = res.data.count;
                    }
                });
            },
            async onWorkshopChange() {
                this.getProcessListByWorkshop();
                await this.getShiftListRequest();
                await this.getCurrentShiftInfoRequest();
                await this.getListRequest();
            },
            async onDateChange() {
                await this.getCurrentShiftInfoRequest();
                this.getListRequest();
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            getShiftListRequest() {
                if (!this.searchParams.workshopId) {
                    this.shiftList = [];
                    return;
                }
                return workforcemanagementShiftPage({
                    workshopId: this.searchParams.workshopId,
                    auditState: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                // this.$set(this.searchParams, 'belongDate', '2024-08-31');
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.searchParams.workshopId) this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.getProcessListByWorkshop();
                try {
                    await this.getShiftListRequest();
                    await this.getCurrentShiftInfoRequest();
                    await this.getListRequest();
                } catch (e) {
                    this.tableLoading = false;
                }
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
<style>
</style>
